package rlyy.framework.netty.server;

import rlyy.framework.netty.config.ApplicationContextUtil;
import rlyy.framework.netty.config.ServerConfig;
import rlyy.framework.netty.inithandler.HttpServerHandler;
import rlyy.framework.netty.inithandler.HttpServerInitializer;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.WebServerException;

public class NettyServer extends AbstractNettyServer implements WebServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final ServerConfig serverConfig;

    public NettyServer(ServerConfig serverConfig) {
        super(serverConfig.getPort());
        this.serverConfig = serverConfig;
    }

    @Override
    public void start() throws WebServerException {
        try{
            super.init();
            super.run();
        } catch (Exception e) {
            throw new WebServerException("tcp server start fail.. cause = " + e,e);
        }
    }

    @Override
    protected void startAfter(ChannelFuture future){
        //Exception thrown
        Throwable cause = future.cause();
        if(cause != null){
            System.exit(-1);
        }

        String logBanner = "\n\n" +
                "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
                "*                                                                                   *\n" +
                "*                                                                                   *\n" +
                "*                   Netty Http Server started on port {" + serverConfig.getPort() + " }                       *\n" +
                "*                                                                                   *\n" +
                "*                                                                                   *\n" +
                "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
        logger.info(logBanner);
    }

    @Override
    protected ChannelHandler newWorkerChannelHandler() {
        HttpServerHandler httpServerHandler = ApplicationContextUtil.getBean(HttpServerHandler.class);
        httpServerHandler.setMaxConnections(serverConfig.getMaxConnections());
        return new HttpServerInitializer(httpServerHandler);
    }

    @Override
    public void stop() throws WebServerException {
        try{
            super.stop();
        } catch (Exception e) {
            throw new WebServerException(e.getMessage(),e);
        }
    }

    @Override
    public int getPort() {
        return serverConfig.getPort();
    }

}
